package connect3.team7.util;

import java.sql.*;
import java.util.Properties;
import java.io.*;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.pool.OracleDataSource;

import connect3.team7.*;

public class DBController {
  private static DBController instance;
  private Connection conn;

  private DBController() {
    super();
    connect();
  }

  public static DBController getInstance() {
    if (instance == null)
      instance = new DBController();

    return instance;
  }

  private void connect() {
    try {
      OracleDataSource ods = new OracleDataSource();
      Properties prop = loadConnProperties();
      ods.setURL(prop.getProperty("jdbc.url"));
      ods.setUser(prop.getProperty("jdbc.username"));
      ods.setPassword(prop.getProperty("jdbc.password"));

      conn = ods.getConnection();
    } catch(SQLException e) {
      e.printStackTrace();
    }
  }

  private Properties loadConnProperties() {
    Properties p = null;

    try {
      p = new Properties();
      p.load(new FileInputStream("../config/dbconnection.properties"));
    } catch (Exception e) {
      e.printStackTrace();
    } 

    return p; 
  }


  public void insertHost(Player host) {
    try {
      PreparedStatement pstmt = conn.prepareStatement("insert into host_listing values (?,?,?,?)");  

      pstmt.setString(1,host.getName());
      pstmt.setString(2,host.getIpAddr());
      pstmt.setInt(3,100);
      pstmt.setInt(4,0);

      pstmt.execute();
      
      pstmt.close();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  class HostListing {
    String host_handle;
    String host_ip;
    int    host_port;
    int    player_slots;
  } 

  public LinkedList<HostListing> getHostListing() {
    LinkedList<HostListing> ret = new LinkedList();

    try {
      Statement stmt = conn.createStatement("select * from host_listing");
  
      ResultSet rs = stmt.executeQuery();
  
      while (rs.next()) {
        HostListing hl = new HostListing(); 
  
        hl.host_handle  = rs.getString(1);
        hl.host_ip      = rs.getString(2);
        hl.host_port    = rs.getInt(3);
        hl.player_slots = rs.getInt(4);
  
        ret.add(hl);      
      }
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
  
    return ret;
  } 
}
